﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Finance
{
    [Navigation("干线流程", "收款管理")]
    [Function("eLogistics.RevenueMachineAccountManagement")]
    [PageTabber(Index = 0, NavigateUrl = "~/Finance/RevenueMachineAccountManagement.aspx", Title = "营收台帐管理", Type = typeof(RevenueMachineAccountManagement))]
    [PageTabber(Index = 1, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-StatementOfAccount.aspx", Title = "对帐管理", Type = typeof(RevenueMachineAccountManagement_StatementOfAccount))]
    [PageTabber(Index = 2, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-Invoice.aspx", Title = "开票管理", Type = typeof(RevenueMachineAccountManagement_Invoice))]
    [PageTabber(Index = 3, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-AccountsReceivable.aspx", Title = "收款管理", Type = typeof(RevenueMachineAccountManagement_AccountsReceivable))]
    public partial class RevenueMachineAccountManagement_AccountsReceivable : NavigationPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                PageQueryAdapter1.PageSize = 20;

                txtConfirmInvoiceDateStart.Text =  DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");

                txtConfirmInvoiceDateEnd.Text =  DateTime.Now.ToString("yyyy-MM-dd");
                this.ddlCustomer.InsertEmptyItem(ListEmptyType.Select);

                ddlCompany.InsertEmptyItem(ListEmptyType.Select);
                if (!this.IsSuperRoles())
                {
                    ddlCompany.SelectedValue = CurrentApplicationContext.CompanyId.ToString();
                    ddlCompany.Enabled = false;
                }

                PageQueryAdapter1.PerformQuery();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ObjectDataSourceCustomers.Selecting += (ds, dsArgs) =>
            {
                dsArgs.InputParameters["areaId"] = CurrentApplicationContext.CompanyId.ToString();
            };


        }


        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {

            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.DataSource = service.SearchRevenueMachineAccountInvoiceByCondition((RevenueMachineAccountInvoiceSearchCriteria)e.Condition, gridOrderList.SortExpression,
                                                      gridOrderList.SortDirection, e.PageSize, e.PageIndex);

        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.RecordCount = service.GetRevenueMachineAccountInvoicesCount((RevenueMachineAccountInvoiceSearchCriteria)e.Condition);
        }

        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var criteria = new RevenueMachineAccountInvoiceSearchCriteria
            {

            };
            if (!MiscUtilities.IsNullOrEmpty(ddlCompany.SelectedValue))
            {
                criteria.AreaId = ddlCompany.SelectedValue.ToGuid();
            }

            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }


            if (!MiscUtilities.IsNullOrEmpty(ddlCustomer.SelectedValue.ToGuid()))
            {
                criteria.CustomerId = ddlCustomer.SelectedValue.ToGuid();
            }
            DateTime? dateStart = null, dateEnd = null;

            if (!string.IsNullOrEmpty(txtConfirmInvoiceDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtConfirmInvoiceDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtConfirmInvoiceDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtConfirmInvoiceDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ConfirmInvoiceDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            dateStart = null; dateEnd = null;

            if (!string.IsNullOrEmpty(txtConfirmAccountsReceiptDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtConfirmAccountsReceiptDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtConfirmAccountsReceiptDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtConfirmAccountsReceiptDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ConfirmAccountsReceivableDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            if (!string.IsNullOrEmpty(txtInvoiceNo.Text))
            {
                criteria.InvoiceNO = txtInvoiceNo.Text.Trim();
            }

            e.Condition = criteria;
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.ReloadCurrentPage();
        }

        protected void gridOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));


                var btnEdit = (ImageButton)e.Row.FindControl("btnEdit");
                if (btnEdit != null)
                {
                    btnEdit.OnClientClick = string.Format("modifyOrder('{0}');return false;", orderId);
                }

                var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
                var isAccountReceiptCompleted =
                    service.GetRevenueMachineAccountInvoice(orderId.ToGuid()).IsAccountReceiptCompleted;

             
                var btnConfirm = (ImageButton)e.Row.FindControl("btnConfirm");
                if (btnConfirm != null)
                {
                    btnConfirm.Visible = !isAccountReceiptCompleted;
                    btnConfirm.OnClientClick = string.Format("confirmOrderInvoice('{0}');return false;", orderId);
                }
            }
        }
        protected void gridProductList_RowDetailCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var issuingOrderId = gridOrderList.DataKeys[e.Row.RowIndex]["Id"].ToString().ToGuid();
                var service = ServiceContainer.GetService<IRevenueMachineAccountService>();

                grdInvoiceReceipt.DataSource = service.GetRevenueMachineAccountInvoiceReceipts(issuingOrderId);
                grdInvoiceReceipt.DataBind();

            }
        }


        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var orderId = fieldOrderId.Value.ToGuid();
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();

            if (service.RemoveRevenueMachineAccountReceipt(orderId))
            {
                PageQueryAdapter1.ReloadCurrentPage();
                Alert("删除成功!");
            }
        }


        protected void btnConfirmOrderInvoice_Click(object sender, EventArgs e)
        {
            var orderId = fieldOrderId.Value.ToGuid();
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();

            if (service.ConfirmRevenueMachineAccountInvoice(orderId))
            {
                PageQueryAdapter1.ReloadCurrentPage();
            }
        }

        


        protected void grdInvoiceReceipt_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));
                var revenueMachineAccountInvoiceId = Convert.ToString(DataBinder.Eval(entity, "RevenueMachineAccountInvoiceId"));
                //check visbile  如果付款结束，不可以删除。增加字段和界面手工确认已付款
                var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
                var isAccountReceiptCompleted =
                    service.GetRevenueMachineAccountInvoice(revenueMachineAccountInvoiceId.ToGuid()).IsAccountReceiptCompleted;

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (btnDelete != null)
                {
                    btnDelete.OnClientClick = string.Format("deleteOrderReceipt('{0}');return false;", orderId);
                    btnDelete.Visible = !isAccountReceiptCompleted;
                }
               
                

            }
        }




    }
}